﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Google.GData.Calendar;
using System.Threading;

namespace Obsady
{
    
    public partial class Form1 : Form
    {
        const string kMailsFilename = "..\\..\\data\\mails.mls";   
        const string kLogFilename = "..\\..\\data\\log.log";
        const string kAuthFilename = "..\\..\\data\\data.dat";
        CExcel _excel = new CExcel();
        string _excelStr; // <-- parsed data from execl to string with separator
        List<ILogger> _log;
        List<string> _tags = new List<string>();
        List<CMatch> _matches = new List<CMatch>();
        CUtils _utils = new CUtils();
        CGoogleCalendar _cal;       
        bool _running = false;       
        EventEntry _previousMatch = null;
        string _login = null;
        string _password = null;
      

        public Form1()
        {
            InitializeComponent();
            _log = new List<ILogger>();
            _log.Add(new CFileLogger(kLogFilename));     // [0]
            _log.Add(new CListBoxLogger(listBox_log));   // [1]
            _utils.readAuthFromFile(kAuthFilename,ref _login,ref _password); // cztaj login i haslo z pliku
            _log[0].Log(this, "Form1 initialized()");             
        }

        public void log(string str)
        {
            foreach (ILogger log in _log)
            {
                log.Log(this,str);
            }

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            if (_login != null && _password != null)
            {
                textBox_email.Text = _login;
                textBox_haslo.Text = _password;
            }
        }

        private void button_przegladaj_Click(object sender, EventArgs e)
        {
            string strr = this.ToString();
            object obj = this;
            openFileDialog_excel.FileName = "test.xls";
            DialogResult result = openFileDialog_excel.ShowDialog();
            if (result == DialogResult.OK) // Test result.
            {
                textBox_sciezka.Text = openFileDialog_excel.FileName;
                _log[0].Log(this,"path set OK");                            
            }else
            {
                _log[0].Log(this,"button_przegladaj_Click result != DialogResult.OK");
            }            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Close();
            _log[0].Log(this,"Form closed");
        }

        private void button_start_Click(object sender, EventArgs e)
        {                                          
            if (!textBox_sciezka.Text.Contains("pliku") || textBox_sciezka.Text.Length == 0)
            {
                log("Start...");
                _running = true;
                if ( checkBox_zapisz.Checked == true )
                    _utils.saveAuthToFile(kAuthFilename, textBox_email.Text, textBox_haslo.Text);
                try
                {
                    _cal = new CGoogleCalendar(_log, textBox_email.Text, textBox_haslo.Text);
                }
                catch (System.IO.FileNotFoundException)
                {
                    MessageBox.Show("Brak pliku mails.mls. Powinien znajdować się w katalogu głównym", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    _running = false;
                    Close();
                }          
                _excelStr = _excel.getText(textBox_sciezka.Text); // <-- parse excel and get string 
                log("Plik z obsadami wczytany.");

                _utils.parse(_excelStr, _tags);
                // dzisiaj jest - sprawdzenie czy poprawny plik dla WzkoszPoznan
                if (_tags[0] != "Liga")
                {
                    _running = false;
                    MessageBox.Show("Nie poprawmy plik dla WZKOSZ Poznań", "Błąd", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                button_start.Enabled = false;
                checkBox_trybTestowy.Enabled = false; 

                _utils.clearAll(_tags);
                _utils.parseTags(_tags, _matches);
                progressBar.Maximum = _matches.Count;

                log("Plik z obsadami sparsowany.");
                log("Dodawanie meczów do Google Kalendarza...");
                if (checkBox_trybTestowy.Checked)
                {
                    button_continue.Enabled = true;
                    startInTestMode();
                }else
                {
                    startInNormalMode();
                }
            }
            else
            {
                MessageBox.Show("Nie podano scieżki do pliku z obsadami.", "Ostrzeżenie", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                log("Nie podano scieżki do pliku z obsadami.");
            }
        }

        private void startInNormalMode()
        {
            try
            {
                foreach (CMatch match in _matches)
                {
                    _cal.CreateEvent(match);
                    log("Mecz stworzony poprawnie.");
                }
            }
            catch (System.ArgumentOutOfRangeException e)
            {
                log("Mecz nie utworzony poprawnie - zły format daty!!!");                
            }             
        }

        private void startInTestMode()
        {
            button_stop_Click(this, new EventArgs());
        }

        private EventEntry runOneMatch(CMatch match)
        {
            try
            {
                return _cal.CreateEvent(match);
            }
            catch (Exception e)
            {
                log("Mecz nie utworzony poprawnie - zły format daty!!!");
                return null;
            }
        }


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (null != _previousMatch && true == checkBox_trybTestowy.Checked)
            {                
                _previousMatch.Delete();
                _previousMatch = null;
                log("Mecz skasowany! - tryb testowy");
            }
            if (_running)
            {
                DialogResult result = MessageBox.Show("Czy jesteś pewien?", "Uwaga!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (DialogResult.Yes == result)
                {        
                                                                  
                }
                else
                {                    
                    e.Cancel = true;                  
                }
            }
            
        }
        // nast. mecz
        private void button_stop_Click(object sender, EventArgs e)
        {
            if (_previousMatch != null)
            {
                log("Mecz skasowany! - tryb testowy");
                _previousMatch.Delete();
            }
            _previousMatch = runOneMatch(_matches[progressBar.Value++]);
            if (progressBar.Value >= progressBar.Maximum)
            {
                button_continue.Enabled = false;
                _running = false;
                log("Wszystkie mecze zostały utworzone! - Koniec");
            }
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            _cal.getAllEventsFromCalendar();
        }

        private void button_browseAdressList_Click(object sender, EventArgs e)
        {
            string strr = this.ToString();
            object obj = this;
            openFileDialog_excel.FileName = "test-listaAdresowa.xls";
            DialogResult result = openFileDialog_excel.ShowDialog();
            if (result == DialogResult.OK) // Test result.
            {
                textBox_pathAdressList.Text = openFileDialog_excel.FileName;
                _log[0].Log(this, "button_browseAdressList_Click path set OK");
            }
            else
            {
                _log[0].Log(this, "button_browseAdressList_Click result != DialogResult.OK");
            }            
        }

        private void button_updateAdressDatabase_Click(object sender, EventArgs e)
        {
            List<string> adressListTag = new List<string>();
            string adressListStr = null;
            log("Aktualizacja bazy danych. Proszę czekać...");
            Cursor.Current = Cursors.WaitCursor;
            try
            {                
                adressListStr = _excel.getText(textBox_pathAdressList.Text);
                _utils.parse(adressListStr, adressListTag);
                _utils.parseAndSaveMails(adressListTag, kMailsFilename);
                Cursor.Current = Cursors.Default;
                log("OK!");
            }
            catch (System.Runtime.InteropServices.COMException ex)
            {
                log("Niepoprawna ścieżka do pliku Lista Adresowa");
                _log[0].Log(this, ex.ToString());
                Cursor.Current = Cursors.Default;
            }     
        }
  
        private void openFileDialog_excel_FileOk(object sender, CancelEventArgs e)
        {

        }

        
    }
}
